package com.example.demo.controller;

import com.example.demo.utils.PassToken;
import com.example.demo.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@CrossOrigin
@RestController
public class CommonController {
    @Value("${uploadPath}")
     String uploadPath;
    //文件上传
     @PostMapping("/upload")
    public ResponseResult<String> uploadFile(MultipartFile file) throws IOException {
         if(file.getSize()>0){
             LocalDate currentDate = LocalDate.now();
             DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
             String formatDate = currentDate.format(formatter);
             File path = new File(uploadPath,formatDate);
             if(!path.exists()){
                 path.mkdirs();
             }
             String newfileName = UUID.randomUUID()+
                     file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
             File f = new File(path,newfileName);
             file.transferTo(f);
             return ResponseResult.createBySuccess(200,"upload/"+formatDate+"/"+newfileName,"上传成功");
         }else{
             return ResponseResult.createBySuccess(500,"","上传失败");
         }
     }

    //文件上传
    @PostMapping("/uploadfiles")
    public ResponseResult<String> uploadFiles(MultipartFile file[]) throws IOException {
         String responsefilename="";
        if(file.length>0){
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formatDate = currentDate.format(formatter);
            File path = new File(uploadPath,formatDate);
            if(!path.exists()){
                path.mkdirs();
            }
            System.out.println(file.length+"   "+"adfafd");
            for(MultipartFile file1:file) {
                String newfileName = UUID.randomUUID() +
                        file1.getOriginalFilename().substring(file1.getOriginalFilename().lastIndexOf("."));
                File f = new File(path, newfileName);
                file1.transferTo(f);
                responsefilename =responsefilename+ "upload/"+formatDate+"/"+newfileName+",";
            }
            return ResponseResult.createBySuccess(200,responsefilename,"上传成功");
        }else{
            return ResponseResult.createBySuccess(500,"","上传失败");
        }
    }


}
